package com.xunqi.crm.web.controller;

import com.xunqi.crm.pojo.User;
import com.xunqi.crm.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
public class IndexController {

    @Resource
    private UserService userService;

    @RequestMapping(value = {"/login", "/"})
    public String index() {
        return "login";
    }

    @RequestMapping(value = "/dologin")
    public String login(String usrName, String usrPassword, HttpServletRequest request, Map<String, Object> map, HttpSession session) {
        User user = null;
        try {
            // 此处不再处理登录,由 Shiro 进行处理
            AuthenticationToken token = new UsernamePasswordToken(usrName,usrPassword);
            SecurityUtils.getSubject().login(token); // 调用 Shiro 认证
            user = (User) SecurityUtils.getSubject().getPrincipal();
            // 注意此处 session.setAttribute 中的 key 的值
            // 需要和 AuthorizationInterceptor 拦截器 session 的 key 的值
            session.setAttribute("user",user);
        }catch (Exception e){
            map.put("msg",e.getMessage());
            return "login";
        }
        return "main";
//        User user = userService.login(usrName, usrPassword);
//        if (user != null) {
//            session.setAttribute("user", user);
//            return "main";
//        } else {
//            model.addAttribute("msg", "用户名或密码错误,登录失败!");
//            return "login";
//        }
    }

    // 退出
    @RequestMapping(value = "/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        // 调用登出方法
        SecurityUtils.getSubject().logout();
        return "login";
    }

    @RequestMapping(value = "/main")
    public String main() {
        return "main";
    }

    @RequestMapping("/403")
    public String unauthorizedRoel(){
        System.out.println("-----------没有权限----------");
        return "403";
    }
}
